package com.example.wechat.controller;

import com.example.wechat.model.WechatMessage;
import com.example.wechat.model.Group;
import com.example.project.entity.User;
import com.example.project.service.CommonService;
import com.example.project.utils.StringUtils;
import com.example.wechat.mapper.WeChatMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/search")
public class SearchController {

	@Autowired
	private WeChatMapper weChatMapper;

	@Autowired
	private CommonService commonService;

	/**
	 * 搜索消息
	 */
	@GetMapping("/messages")
	public ResponseEntity<Map<String, Object>> searchMessages(@RequestParam("keyword") String keyword,
			@RequestParam(value = "chatType", required = false) String chatType,
			@RequestParam(value = "targetId", required = false) String targetId,
			@RequestParam(value = "startDate", required = false) String startDate,
			@RequestParam(value = "endDate", required = false) String endDate, Principal principal) {

		try {
			String currentUser = principal.getName();
			List<WechatMessage> searchResults = new ArrayList<>();

			// 根据搜索条件查询消息
			if (chatType != null && targetId != null) {
				// 指定聊天对象搜索
				if ("user".equals(chatType)) {
					// 私聊消息搜索
					searchResults = weChatMapper.findByContentContainingAndFromOrTo(keyword, currentUser);

				} else if ("group".equals(chatType)) {
					// 群聊消息搜索
					searchResults = weChatMapper.findByContentContainingAndFromOrTo(keyword, currentUser);

					// 过滤指定群组的消息
					searchResults = searchResults.stream()
							.filter(msg -> msg.getGroupId() != null && msg.getGroupId().toString().equals(targetId))
							.collect(Collectors.toList());
				}
			} else {
				// 全局搜索
				searchResults = weChatMapper.findByContentContainingAndFromOrTo(keyword, currentUser);
			}

			// 日期过滤
			if (startDate != null && endDate != null) {
				// 这里简化处理，实际应该使用数据库日期查询
				searchResults = searchResults.stream().filter(msg -> {
					// 假设日期格式为 "yyyy-MM-dd"
					String msgDate = msg.getSendTime().toLocalDate().toString();
					return msgDate.compareTo(startDate) >= 0 && msgDate.compareTo(endDate) <= 0;
				}).collect(Collectors.toList());
			}

			// 按时间排序（最新在前）
			searchResults.sort((m1, m2) -> m2.getSendTime().compareTo(m1.getSendTime()));

			// 统计信息
			Map<String, Object> stats = new HashMap<>();
			stats.put("totalResults", searchResults.size());
			stats.put("keyword", keyword);

			// 按聊天对象分组
			Map<String, List<WechatMessage>> groupedResults = searchResults.stream()
					.collect(Collectors.groupingBy(msg -> {
						if (msg.getGroupId() != null) {
							return "group_" + msg.getGroupId();
						} else {
							return "user_" + msg.getFromUser();
						}
					}));
			List<User> userList = commonService.getUserList();
			// 根据keyword对userList中的userName进行模糊匹配
			List<User> filteredUserList = userList.stream()
					.filter(user -> user.getUserName() != null
							&& user.getUserName().toLowerCase().contains(keyword.toLowerCase()))
					.collect(Collectors.toList());

			Map<String, Object> result = new HashMap<>();
			result.put("success", true);
			result.put("messages", searchResults);
			result.put("groupedResults", groupedResults);
			result.put("filteredUsers", filteredUserList);
			result.put("stats", stats);

			return ResponseEntity.ok(result);

		} catch (Exception e) {
			Map<String, Object> result = new HashMap<>();
			result.put("success", false);
			result.put("error", "搜索失败: " + e.getMessage());
			return ResponseEntity.badRequest().body(result);
		}
	}

	/**
	 * 获取消息历史
	 */
	@GetMapping("/history")
	public ResponseEntity<Map<String, Object>> getMessageHistory(
			@RequestParam(value = "chatType", required = false) String chatType,
			@RequestParam(value = "targetId", required = false) String targetId,
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "size", defaultValue = "20") int size, Principal principal) {

		try {
			String currentUser = principal.getName();
			List<WechatMessage> historyMessages = new ArrayList<>();

			if (chatType != null && targetId != null) {
				if ("user".equals(chatType)) {
					// 私聊历史
//					historyMessages = getPrivateChatHistory(currentUser, targetId, page, size);
				} else if ("group".equals(chatType)) {
					// 群聊历史
					historyMessages = getGroupChatHistory(targetId, page, size);
				}
			} else {
				// 所有聊天历史（按时间倒序）
				historyMessages = getAllChatHistory(currentUser, page, size);
			}

			// 统计信息
			Map<String, Object> stats = new HashMap<>();
			stats.put("currentPage", page);
			stats.put("pageSize", size);
			stats.put("totalMessages", historyMessages.size());

			// 分页信息
			boolean hasMore = historyMessages.size() == size;

			Map<String, Object> result = new HashMap<>();
			result.put("success", true);
			result.put("messages", historyMessages);
			result.put("stats", stats);
			result.put("hasMore", hasMore);

			return ResponseEntity.ok(result);

		} catch (Exception e) {
			Map<String, Object> result = new HashMap<>();
			result.put("success", false);
			result.put("error", "获取历史消息失败: " + e.getMessage());
			return ResponseEntity.badRequest().body(result);
		}
	}

	/**
	 * 获取私聊历史
	 */
//	private List<WechatMessage> getPrivateChatHistory(String currentUser, String targetUser, int page, int size) {
//		List<WechatMessage> allMessages = weChatMapper.findByFromOrTo(currentUser, targetUser);
//
//		// 过滤私聊消息
//		allMessages = allMessages.stream()
//				.filter(msg -> (msg.getFromUser().equals(currentUser) && msg.getTo().equals(targetUser))
//						|| (msg.getFromUser().equals(targetUser) && msg.getTo().equals(currentUser)))
//				.sorted((m1, m2) -> m2.getSendTime().compareTo(m1.getSendTime())).collect(Collectors.toList());
//
//		return paginateList(allMessages, page, size);
//	}

	/**
	 * 获取群聊历史
	 */
	private List<WechatMessage> getGroupChatHistory(String groupId, int page, int size) {
		List<WechatMessage> allMessages = weChatMapper.findByFromOrTo(null, null); // 实际应该实现群聊消息查询

		// 过滤群聊消息
		allMessages = allMessages.stream()
				.filter(msg -> msg.getGroupId() != null && msg.getGroupId().toString().equals(groupId))
				.sorted((m1, m2) -> m2.getSendTime().compareTo(m1.getSendTime())).collect(Collectors.toList());

		return paginateList(allMessages, page, size);
	}

	/**
	 * 获取所有聊天历史
	 */
	private List<WechatMessage> getAllChatHistory(String currentUser, int page, int size) {
		List<WechatMessage> allMessages = weChatMapper.findByFromOrTo(currentUser, null);

		// 按时间倒序排序
		allMessages.sort((m1, m2) -> m2.getSendTime().compareTo(m1.getSendTime()));

		return paginateList(allMessages, page, size);
	}

	/**
	 * 列表分页
	 */
	private List<WechatMessage> paginateList(List<WechatMessage> list, int page, int size) {
		int start = (page - 1) * size;
		if (start >= list.size()) {
			return new ArrayList<>();
		}

		int end = Math.min(start + size, list.size());
		return list.subList(start, end);
	}

	/**
	 * 获取聊天记录统计
	 */
	@GetMapping("/stats")
	public ResponseEntity<Map<String, Object>> getChatStats(Principal principal) {
		try {
			String currentUser = principal.getName();

			// 获取所有消息
			List<WechatMessage> allMessages = weChatMapper.findByFromOrTo(currentUser, null);

			// 统计信息
			Map<String, Object> stats = new HashMap<>();

			// 总消息数
			stats.put("totalMessages", allMessages.size());

			// 未读消息数
//			long unreadCount = allMessages.stream().filter(msg -> msg.getTo().equals(currentUser) && !msg.getIsRead())
//					.count();
//			stats.put("unreadMessages", unreadCount);
//			// 按聊天对象统计
//			Map<String, Long> chatStats = allMessages.stream().collect(Collectors.groupingBy(msg -> {
//				if (msg.getGroupId() != null) {
//					return "group_" + msg.getGroupId();
//				} else {
//					String otherUser = msg.getFromUser().equals(currentUser) ? msg.getTo() : msg.getFromUser();
//					return "user_" + otherUser;
//				}
//			}, Collectors.counting()));
//			stats.put("chatStats", chatStats);

			// 最近活跃时间
			if (!allMessages.isEmpty()) {
				LocalDateTime latestMessageTime = allMessages.get(0).getSendTime();
				stats.put("latestActivity", latestMessageTime);
			}

			Map<String, Object> result = new HashMap<>();
			result.put("success", true);
			result.put("stats", stats);

			return ResponseEntity.ok(result);

		} catch (Exception e) {
			Map<String, Object> result = new HashMap<>();
			result.put("success", false);
			result.put("error", "获取统计信息失败: " + e.getMessage());
			return ResponseEntity.badRequest().body(result);
		}
	}

	/**
	 * 导出聊天记录
	 */
	@GetMapping("/export")
	public ResponseEntity<String> exportChatHistory(@RequestParam(value = "chatType", required = false) String chatType,
			@RequestParam(value = "targetId", required = false) String targetId, Principal principal) {

		try {
			String currentUser = principal.getName();
			List<WechatMessage> messagesToExport = new ArrayList<>();

			if (chatType != null && targetId != null) {
				if ("user".equals(chatType)) {
//					messagesToExport = getPrivateChatHistory(currentUser, targetId, 1, Integer.MAX_VALUE);
				} else if ("group".equals(chatType)) {
					messagesToExport = getGroupChatHistory(targetId, 1, Integer.MAX_VALUE);
				}
			} else {
				messagesToExport = getAllChatHistory(currentUser, 1, Integer.MAX_VALUE);
			}

			// 生成导出文本
			StringBuilder exportContent = new StringBuilder();
			exportContent.append("聊天记录导出\n");
			exportContent.append("导出时间: ").append(LocalDateTime.now()).append("\n");
			exportContent.append("用户: ").append(currentUser).append("\n\n");

			for (WechatMessage message : messagesToExport) {
				exportContent.append("[").append(message.getSendTime()).append("] ").append(message.getFromUser())
						.append(": ").append(message.getContent()).append("\n");
			}

			return ResponseEntity.ok(exportContent.toString());

		} catch (Exception e) {
			return ResponseEntity.badRequest().body("导出失败: " + e.getMessage());
		}
	}
}